package com.jdew.thkj.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;

import com.jdew.thkj.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.jdew.thkj.R.id.progress;

/**
 * Created by yangyang on 2017/12/8.
 */

public class UpdataApp {
    public static String uri = "http://www.taohuikeji.com/Attachment/taolehui.apk";

    public static void showDialogUpdate(final Context context, String tit) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        SimpleDateFormat sdf = new SimpleDateFormat( "yy.MM.dd" );
        Date d = new Date();
        String dateNowStr = sdf.format( d );
        AlertDialog.Builder builder = new AlertDialog.Builder( context );
        // 设置提示框的标题
        builder.setTitle( dateNowStr + "系统更新公告" ).
                // 设置提示框的图标
                        setIcon( R.mipmap.logo ).
                // 设置要显示的信息
                        setMessage( tit ).
                // 设置确定按钮
                        setPositiveButton( "前往更新", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        loadNewVersionProgress( context );//下载最新的版本程序
                    }
                } ).

                // 设置取消按钮,null是什么都不做，并关闭对话框
                        setNegativeButton( "暂不更新", null );

        // 生产对话框
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        // 显示对话框
        alertDialog.getButton( alertDialog.BUTTON_NEGATIVE ).setTextColor( Color.RED );
        alertDialog.getButton( alertDialog.BUTTON_POSITIVE ).setTextColor( Color.RED );

    }

    private static void loadNewVersionProgress(final Context context) {
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog( context );
        pd.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
        pd.setMessage( "正在下载更新" );
        pd.setProgressDrawable( context.getResources().getDrawable( R.drawable.progressbar ) );
        pd.setProgress( progress );
        pd.setCancelable( true );
        pd.show();
        //启动子线程下载任务
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer( pd );
                    sleep( 3000 );
                    installApk( context, file );
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 安装apk
     */
    protected static void installApk(Context context, File file) {
        Intent install = new Intent( Intent.ACTION_VIEW );
        install.setDataAndType( Uri.fromFile( file ), "application/vnd.android.package-archive" );
        install.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        context.startActivity( install );
    }

    /**
     * 从服务器获取apk文件的代码
     * 传入网址uri，进度条对象即可获得一个File文件
     * （要在子线程中执行哦）
     */
    public static File getFileFromServer(ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED )) {
            URL url = new URL( uri );
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout( 5000 );
            //获取到文件的大小
            pd.setMax( conn.getContentLength() );
            InputStream is = conn.getInputStream();
            long time = System.currentTimeMillis();//当前时间的毫秒数
            File file = new File( Environment.getExternalStorageDirectory(), time + "updata.apk" );
            FileOutputStream fos = new FileOutputStream( file );
            BufferedInputStream bis = new BufferedInputStream( is );
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read( buffer )) != -1) {
                fos.write( buffer, 0, len );
                total += len;
                //获取当前下载量
                pd.setProgress( total );
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

}
